﻿using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Net.Http.Json;
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Web;
using AntDesign;
using ImoviesBlazorAntPro.Shared.Dtos;
using ImoviesBlazorAntPro.Shared.Utils;
using System;

namespace ImoviesBlazorAntPro.Client.Pages.Admin
{
    public partial class AnnualReviewManage
    {
        [Inject]
        HttpClient HttpClient { get; set; }
        [Inject]
        IMessageService MessageService { get; set; }
        [Inject]
        ModalService ModalService { get; set; }

        private string _videoCate;
        private bool _loading = false;


        private List<AnnualReviewDto> dataList = new List<AnnualReviewDto>();
        private IEnumerable<AnnualReviewDto> selectedRows;


        /// <summary>
        /// 显示添加对话框
        /// </summary>
        private void ShowAddModal()
        {
            if (string.IsNullOrEmpty(_videoCate))
            {
                MessageService.Warning("请选择分类", 1.5);
                return;
            }
            addModel.Comment = string.Empty;
            _addModalVisible = true;
        }


        /// <summary>
        /// 显示编辑对话框
        /// </summary>
        /// <param name="obj"></param>
        private void ShowEditModal(AnnualReviewDto obj)
        {
            editModel.Id = obj.Id;
            editModel.Year = obj.Year;
            editModel.Comment = obj.Comment;
            _editModalVisible = true;
        }


        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="id"></param>
        private async Task ConfirmDeleteAsync(uint id)
        {
            var res = await HttpClient.DeleteAsync($"/api/annualReview/{id}");
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }
            MessageService.Success("操作成功", 1.5);
            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/annualReview/{_videoCate}");
            dataList = JsonSerializer.Deserialize<List<AnnualReviewDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        private async void BatchDelete()
        {
            if (selectedRows == null)
            {
                MessageService.Warning("请选择年评", 2);
                return;
            }

            ModalService.Confirm(new ConfirmOptions()
            {
                Title = "确定进行批量删除吗?",
                OkType = "danger",
                OkText = "确定",
                CancelText = "取消",
                OnOk = async (e) =>
                {
                    var ids = selectedRows.Select(x => x.Id).ToList();
                    var res = await HttpClient.PostAsJsonAsync("/api/annualReview/batchDetele", ids);
                    if (!res.IsSuccessStatusCode)
                    {
                        MessageService.Error("操作失败", 2);
                        return;
                    }
                    MessageService.Success("操作成功", 1.5);
                    // 重载数据
                    var resp = await HttpClient.GetAsync($"/api/annualReview/{_videoCate}");
                    dataList = JsonSerializer.Deserialize<List<AnnualReviewDto>>(await resp.Content.ReadAsStringAsync(),
                     new JsonSerializerOptions
                     {
                         PropertyNameCaseInsensitive = true,
                         IncludeFields = true,
                     });
                },
            });
        }


        /// <summary>
        /// 视频分类选择切换事件
        /// </summary>
        /// <param name="vid"></param>
        private async Task VideoCateSelectedChangeAsync(string vcate)
        {
            _loading = true;
            dataList.Clear();
            var resp = await HttpClient.GetAsync($"/api/annualReview/{vcate}");
            dataList = JsonSerializer.Deserialize<List<AnnualReviewDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            _loading = false;
        }


        /// <summary>
        /// 加载完毕事件
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            HttpClient.DefaultRequestHeaders.Add("X-Req-Origin", "Admin");
            await base.OnInitializedAsync();
        }


        #region 添加表单相关操作

        private bool _addModalVisible = false;
        private AnnualReviewForCreateDto addModel = new AnnualReviewForCreateDto();
        private Form<AnnualReviewForCreateDto> _addForm;

        /// <summary>
        /// 提交失败
        /// </summary>
        /// <param name="editContext"></param>
        private void OnAddFormFinishFailed(EditContext editContext)
        {
            //Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
        }


        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="e"></param>
        private void HandleAddModalCancel(MouseEventArgs e)
        {
            _addModalVisible = false;
        }


        /// <summary>
        /// 表单提交后关闭 modal
        /// </summary>
        /// <param name="editContext"></param>
        private void OnAddFormFinish(EditContext editContext)
        {
            _addModalVisible = false;
        }

        /// <summary>
        /// 点击modal的OK按钮提交表单
        /// </summary>
        /// <param name="e"></param>
        private async Task HandleAddModalOkAsync(MouseEventArgs e)
        {
            if (!_addForm.Validate())
            {
                return;
            }
            AnnualReviewsVideoCate cate = (AnnualReviewsVideoCate)Enum.Parse(typeof(AnnualReviewsVideoCate), _videoCate);
            var data = new AnnualReviewForCreateDto
            {
                VideoCate = cate,
                Year = addModel.Year,
                Comment = addModel.Comment,
            };
            var res = await HttpClient.PostAsJsonAsync<AnnualReviewForCreateDto>("/api/annualReview", data);
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }
            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/annualReview/{_videoCate}");
            dataList = JsonSerializer.Deserialize<List<AnnualReviewDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            MessageService.Success("操作成功", 1.5);
            _addForm.Reset();
            _addModalVisible = false;
        }

        #endregion




        #region 编辑表单相关操作

        bool _editModalVisible = false;
        private AnnualReviewForUpdateDto editModel = new AnnualReviewForUpdateDto();
        private Form<AnnualReviewForUpdateDto> _editForm;

        /// <summary>
        /// 提交失败
        /// </summary>
        /// <param name="editContext"></param>
        private void OnEditFormFinishFailed(EditContext editContext)
        {
            //Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
        }


        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="e"></param>
        private void HandleEditModalCancel(MouseEventArgs e)
        {
            _editModalVisible = false;
        }


        /// <summary>
        /// 表单提交后关闭 modal
        /// </summary>
        /// <param name="editContext"></param>
        private void OnEditFormFinish(EditContext editContext)
        {
            _editModalVisible = false;
        }

        /// <summary>
        /// 点击modal的OK按钮提交表单
        /// </summary>
        /// <param name="e"></param>
        private async Task HandleEditModalOkAsync(MouseEventArgs e)
        {
            if (!_editForm.Validate())
            {
                return;
            }
            var data = new AnnualReviewForUpdateDto
            {
                Id = editModel.Id,
                Year = editModel.Year,
                Comment = editModel.Comment,
            };
            var res = await HttpClient.PutAsJsonAsync<AnnualReviewForUpdateDto>("/api/annualReview", data);
            if (!res.IsSuccessStatusCode)
            {
                await MessageService.Error("操作失败", 2);
                return;
            }

            // 重载数据
            var resp = await HttpClient.GetAsync($"/api/annualReview/{_videoCate}");
            dataList = JsonSerializer.Deserialize<List<AnnualReviewDto>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });
            MessageService.Success("操作成功", 1.5);
            _editForm.Reset();
            _editModalVisible = false;
        }

        #endregion
    }
}
